package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;


    /**
     * 保存本地交易记录
     *
     * @param paymentType:支付类型 1301-订单 1302-充值
     * @param orderNo:         订单编号
     * @param userId:          用户ID
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo) {
        //1.根据订单编号查询本地交易记录是否存在 如果存在则返回即可
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        queryWrapper.last("limit 1");
        PaymentInfo paymentInfo = this.getOne(queryWrapper);
        if (paymentInfo != null) {
            return paymentInfo;
        }
        //2.创建本地交易记录封装各项属性并且保存
        paymentInfo = new PaymentInfo();
        //2.1 对基本属性赋值
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        //1401-未支付 1402-已支付
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        //判断本次交易类型是订单还是充值
        //2.2 处理交易类型是订单
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            //2.2.1 远程调用“订单”服务获取订单信息
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo, "订单不存在");
            String orderStatus = orderInfo.getOrderStatus();
            //2.2.2 判断订单状态是否合法（未支付）
            Assert.state(SystemConstant.ORDER_STATUS_UNPAID.equals(orderStatus), "订单状态有误！");
            //2.2.3 封装用户ID，金额，内容
            paymentInfo.setUserId(orderInfo.getUserId());
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            paymentInfo.setContent(orderInfo.getOrderTitle());
        } else if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            //2.3 处理交易类型是充值
            //2.3.1 远程调用“账户”服务获取充值信息
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo, "充值记录不存在！");
            //2.3.2 判断充值记录状态是否合法（未支付）
            Assert.state(SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus()), "充值记录状态有误");
            //2.3.3 封装用户ID，金额，内容
            paymentInfo.setUserId(rechargeInfo.getUserId());
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfo.setContent("充值金额：" + rechargeInfo.getRechargeAmount());
        }
        //TODO 以下三个字段 微信端交易编号、回调内容、回调时间 再支持成功后微信回调中才能更新
        //paymentInfo.setOutTradeNo();
        //paymentInfo.setCallbackTime();
        //paymentInfo.setCallbackContent();
        this.save(paymentInfo);
        //3.返回本地交易记录
        return paymentInfo;
    }

    /**
     * 修改本地交易记录
     *
     * @param orderNo     订单编号
     * @param transaction 微信返回交易对象
     */
    @Override
    public void updatePaymentInfo(String orderNo, Transaction transaction) {
        //1.根据订单编号查询本地交易记录
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = this.getOne(queryWrapper);
        if (SystemConstant.PAYMENT_STATUS_PAID.equals(paymentInfo.getPaymentStatus())) {
            return;
        }
        //2.更新本地交易记录：微信交易编号，回调时间，回调内容，支付状态：已支付
        paymentInfo.setOutTradeNo(transaction.getTransactionId());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(transaction.toString());
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        this.updateById(paymentInfo);
        //支付类型：1301-订单 1302-充值
        //3.处理本地交易记录对应订单-修改订单状态
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentInfo.getPaymentType())) {
            //3.1 远程调用订单服务修改订单支付状态及虚拟物品发货
            Result result = orderFeignClient.orderPaySuccess(orderNo);
            //3.2 判断远程调用结果业务状态码
            if (200 != result.getCode()) {
                throw new GuiguException(500, "更新订单有误！");
            }
        } else if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentInfo.getPaymentType())) {
            //4.处理本地交易记录对应充值-修改充值状态
            //4.1 远程调用账户服务完成充值成功业务
            Result result = accountFeignClient.rechargePaySuccess(orderNo);
            //4.2 判断远程调用结果业务状态码
            if (200 != result.getCode()) {
                throw new GuiguException(500, "充值有误！");
            }
        }
    }
}
